package com.library.controller;

import com.library.model.Borrowing;
import com.library.service.BorrowingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/api/borrowings")
public class BorrowingController {
    private final BorrowingService borrowingService;

    @Autowired
    public BorrowingController(BorrowingService borrowingService) {
        this.borrowingService = borrowingService;
    }

    @GetMapping
    public List<Borrowing> getAllBorrowings() {
        return borrowingService.getAllBorrowings();
    }

    @GetMapping("/{id}")
    public ResponseEntity<Borrowing> getBorrowingById(@PathVariable Long id) {
        return borrowingService.getBorrowingById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    @GetMapping("/reader/{readerId}")
    public List<Borrowing> getBorrowingsByReaderId(@PathVariable Long readerId) {
        return borrowingService.getBorrowingsByReaderId(readerId);
    }

    @GetMapping("/book/{bookId}")
    public List<Borrowing> getBorrowingsByBookId(@PathVariable Long bookId) {
        return borrowingService.getBorrowingsByBookId(bookId);
    }

    @GetMapping("/active")
    public List<Borrowing> getActiveBorrowings() {
        return borrowingService.getActiveBorrowings();
    }

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public ResponseEntity<Borrowing> borrowBook(@Valid @RequestBody Borrowing borrowing) {
        try {
            Borrowing newBorrowing = borrowingService.borrowBook(borrowing);
            return ResponseEntity.status(HttpStatus.CREATED).body(newBorrowing);
        } catch (IllegalStateException | IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(null);
        }
    }

    @PutMapping("/return/{id}")
    public ResponseEntity<Borrowing> returnBook(@PathVariable Long id, @Valid @RequestBody Borrowing borrowing) {
        try {
            Borrowing updatedBorrowing = borrowingService.returnBook(id, borrowing);
            return ResponseEntity.ok(updatedBorrowing);
        } catch (IllegalStateException | IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(null);
        }
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteBorrowing(@PathVariable Long id) {
        borrowingService.deleteBorrowing(id);
        return ResponseEntity.noContent().build();
    }
}
